package com.hunter.util;

import java.util.LinkedList;
import java.util.List;

/**
 * 2010-9-28 下午05:09:56<br>
 * 索引管理器,包括有索引目录的添加,删除与查看
 * <p>
 * 在创建索引后调用添加<br>
 * 在索引删除后调用删除<br>
 * 可获取已创建索引的所有目录<br>
 * 可检查对应的路径是否已存在
 * 
 * @author mkk
 */
public class IndexManager {

	// only object
	private static IndexManager man = new IndexManager();
	// 缓存已创建的目录信息
	private List<String> list = null;
	// 原始信息
	private String originPaths = null;

	/**
	 * private constructor
	 */
	private IndexManager() {
		list = new LinkedList<String>();
		originPaths = PropertiesUtil.getIndexPaths();
		if (!"".equals(originPaths)) {
			//More index path split by characters '@@#'
			String[] paths = originPaths.split("@@#");
			for (int i = 0; i < paths.length; i++) {
				list.add(paths[i]);
			}
		}
	}

	/**
	 * 获取唯一对象
	 * 
	 * @return
	 */
	public static IndexManager getIndexManager() {
		return man;
	}

	/**
	 * 添加路径,在创建索引后调用此方法 若添加的路径已经存在则不添加
	 * 
	 * @param path
	 *            索引全路径
	 * @return
	 */
	public boolean add(String path) {
		if (path == null || path.trim().length() == 0) {
			return false;
		}
		if (list.contains(path)) {
			return false;
		}
		list.add(path);
		if ("".equals(originPaths)) {
			this.originPaths = path;
		} else {
			this.originPaths += ("@@#" + path);
		}
		PropertiesUtil.saveIndexPaths(originPaths);
		return true;
	}

	/**
	 * 删除路径,在删除索引文件后调用此方法
	 * 
	 * @param path
	 *            索引全路径
	 * @return
	 */
	public boolean remove(String path) {
		if (path == null || path.trim().length() == 0) {
			return false;
		}
		if (list.remove(path)) {
			StringBuilder sb = new StringBuilder();
			for (String s : list) {
				sb.append(s + "@@#");
			}
			if (list.size() > 0) {
				this.originPaths = sb.toString().substring(0,
						sb.toString().lastIndexOf("@@#"));
			} else {
				this.originPaths = "";
			}
			PropertiesUtil.saveIndexPaths(originPaths);
			return true;
		}
		return false;
	}

	/**
	 * 获取已创建索引的所有目录列表
	 * 
	 * @return
	 */
	public List<String> getAllPath() {
		return list;
	}

	/**
	 * 清空所有路径
	 * 
	 * @return
	 */
	public boolean cleanAllPath() {
		list.clear();
		this.originPaths = "";
		PropertiesUtil.saveIndexPaths(originPaths);
		return true;
	}

	/**
	 * 检查指定的路径是否存在
	 * 
	 * @param path
	 *            索引全路径
	 * @return
	 */
	public boolean isPathExist(String path) {
		if (path == null) {
			return false;
		}
		if (list.contains(path)) {
			return true;
		}
		return false;
	}

}
